package com.hailiao.beidou.message.service

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.PowerManager
import com.d10ng.compose.model.UiViewModelManager
import com.d10ng.datelib.curTime
import com.d10ng.datelib.toDateStr
import com.hailiao.beidou.message.MainActivity
import com.hailiao.beidou.message.R
import com.hailiao.beidou.message.app
import com.hailiao.beidou.message.bd.Beidou
import com.hailiao.beidou.message.data.store.getSpfProtoVersion
import com.hailiao.beidou.message.utils.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.schedule

/**
 * 位置上报服务
 * @Author d10ng
 * @Date 2024/3/13 13:45
 */
class SendLocationService: Service() {

    companion object {
        private const val TAG = "SendLocationService"
        // 位置上报ID
        private const val NOTIFY_ID = 0x1FFFFFFF
        // 上次发送成功时间
        val lastSuccessTimeTextFlow = MutableStateFlow("--")
        // 目标卡号
        var targetCard: String = ""
    }

    // 发送定时器
    private var timer: Timer? = null

    // 唤醒锁
    private var wakeLock: PowerManager.WakeLock? = null

    override fun onCreate() {
        super.onCreate()
        Logger.i("$TAG onCreate")
    }
    @SuppressLint("WakelockTimeout")
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Logger.i("$TAG onStartCommand")
        // 创建通知
        val notifyIntent = Intent(app, MainActivity::class.java).apply {
            this.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
            action = curTime.toString()
        }
        val pendingIntent =
            PendingIntent.getActivity(app, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        val builder = createNotification(
            type = NotificationType.LOCATION_REPORT_MSG,
            notifyId = NOTIFY_ID,
            title = getString(R.string.app_name),
            content = "正在进行连续位置汇报",
            iconResId = R.mipmap.ic_launcher_round,
            tapIntent = pendingIntent
        )
        startForeground(NOTIFY_ID, builder.build())

        // 创建唤醒锁
        val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$packageName:wake:loc")
        wakeLock?.acquire()

        // 开始上报
        // 计算延迟时间，北斗通道为等待时间，公网则为0
        val delayTime = Beidou.waitTimeFlow.value
        // 循环发送时间差为北斗卡频度
        val sendIntervalTime = Beidou.cardFlow.value.frequency * 1000L
        // 开始循环发送
        timer?.cancel()
        timer = Timer().apply {
            schedule(delayTime * 1000L, sendIntervalTime) {
                CoroutineScope(Dispatchers.IO).launch {
                    if (Beidou.sendLocation(getSpfProtoVersion(), targetCard)) {
                        lastSuccessTimeTextFlow.value = curTime.toDateStr()
                        UiViewModelManager.showSuccessToast("发送成功")
                    } else {
                        UiViewModelManager.showFailToast("发送失败")
                    }
                }
            }
        }
        return START_STICKY
    }

    override fun onBind(p0: Intent?): IBinder? {
        Logger.i("$TAG onBind")
        return null
    }

    override fun onDestroy() {
        Logger.i("$TAG onDestroy")
        // 释放唤醒锁
        wakeLock?.release()
        // 停止上报
        timer?.cancel()
        super.onDestroy()
    }
}